﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceOfSansar.Models;

namespace ServiceOfSansar.Auth
{
    internal class TokenManager
    {
        internal static string Create(int Id)
        {
            using(SansarEntities db=new SansarEntities())
            {
                Token t=new Token(){ AccessTime=DateTime.Now, UserId=Id, eToken=Guid.NewGuid()};
                db.Tokens.AddObject(t);
                db.SaveChanges();
                return t.eToken.ToString();
            }
        }

        internal static bool CheckAccess(string token)
        {
            using (SansarEntities db = new SansarEntities())
            {
                Guid id;
                if (!Guid.TryParse(token,out id))
                    return false;
                
                var t = db.Tokens.SingleOrDefault(w => w.eToken == id);
                if (t == null)
                    return false;

                t.AccessTime = DateTime.Now;
                db.SaveChanges();
                return true;
            }            
        }

        internal static void Kills()
        {
            using (SansarEntities db = new SansarEntities())
            {
                int minutes = int.Parse(System.Configuration.ConfigurationManager.AppSettings["TimeOut"].ToString());
                var time=DateTime.Now.AddMinutes(minutes*-1);
                var list = db.Tokens.Where(w => w.AccessTime < time).ToArray();
                for (int i = 0; i < list.Count(); i++)
                {
                    db.Tokens.DeleteObject(list[i]);
                }
                db.SaveChanges();
            } 
        }
    }
}
